package com.ysccc.shares.web;

import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysccc.shares.entity.SharesSaleAlert;
import com.ysccc.shares.manager.SharesSaleAlertManager;
import com.ysccc.shares.web.vo.SharesSaleAlertVo;
import com.ysccc.spring.boot.starter.sqldb.repository.support.FilterParamBuilder;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder.JsonData;
import com.ysccc.tools.Dates;

@RestController
@RequestMapping("/shares/sale/alert")
public class SharesSaleAlertController {
	
	@Autowired
	private SharesSaleAlertManager sharesSaleAlertManager;

	@GetMapping("/check")
	public JsonData checkAlert() {
		Calendar now = Calendar.getInstance();
		int hour = now.get(Calendar.HOUR_OF_DAY);
		Date beginTime = Dates.clearTime(now.getTime());
		Date endTime = Dates.lastScend(now.getTime());
		if (hour < 15) { // 下午三点前，查看前一天的报警
			beginTime = Dates.addDay(beginTime, -3);
			endTime = Dates.addDay(endTime, -3);
		}
		Optional<SharesSaleAlert> alert = sharesSaleAlertManager.findOne(FilterParamBuilder.create().eq("status", Boolean.TRUE).gte("day", beginTime).lte("day", endTime).build());
		if (alert.isPresent()) {
			return JsonBuilder.of(new SharesSaleAlertVo(alert.get())).build(JsonData.class);
		} else {
			throw new RuntimeException("没记录");
		}
	}
	
	@PostMapping("/close/{id}")
	public JsonData closeALert(@PathVariable Long id) {
		SharesSaleAlert alert = sharesSaleAlertManager.getOne(id);
		if (alert != null) {
			alert.setStatus(Boolean.FALSE);
			sharesSaleAlertManager.save(alert);
		}
		return JsonBuilder.of().build(JsonData.class);
	}
}
